package Offer.offer2017;

import domain.TreeNode;

/**
 * 二叉树的深度 及判断是否是平衡二叉树
 * Created by 雷文康 on 2018/1/4.
 */
public class Test39 {
    /**
     * 是否是平衡二叉树
     */
    public static boolean isBalanceBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        int left = treeDepth(root.left);
        int right = treeDepth(root.right);
        if (left - right > 1 || left - right < -1) {
            return false;
        }
        return isBalanceBST(root.left) && isBalanceBST(root.right);
    }

    /**
     * 二叉树的深度
     *
     * @param root
     * @return
     */
    private static int treeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = treeDepth(root.left);
        int right = treeDepth(root.right);
        return left > right ? (left + 1) : (right + 1);
    }


    /**
     * 是否是平衡二叉树
     */
    public static boolean isBalanceBST2(TreeNode root) {
        return depth(root) != -1;
    }

    private static int depth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int left = depth(root.left);
        if (left == -1) {
            return -1;
        }

        int right = depth(root.right);
        if (right == -1) {
            return -1;
        }

        return Math.abs(left - right) <= 1 ? Math.max(left, right) + 1 : -1;
    }
}
